from flask import g, jsonify
from flask_httpauth import HTTPBasicAuth
from app.models import User
from . import api
from app.errors import unauthorized, forbidden

httpAuth = HTTPBasicAuth()


@httpAuth.verify_password
def verify_password(name, password):
    if name == '':
        return False
    if password == '':
        g.current_user = User.verify_auth_token(name)
        g.token_used = True
        return g.current_user is not None
    user = User.query.filter_by(name=name).first()
    if not user:
        return False
    g.current_user = user
    g.token_used = False
    return user.verify_password(password)


@httpAuth.error_handler
def auth_error():
    return unauthorized('Invalid credentials')


@api.before_request
@httpAuth.login_required
def before_request():
    if not g.current_user.is_anonymous and \
            not g.current_user.confirmed:
        return forbidden('Unconfirmed account')


@api.route('/tokens/', methods=['POST'])
def get_token():
    if g.current_user.is_anonymous or g.token_used:
        return unauthorized('Invalid credentials')
    return jsonify({'token': g.current_user.generate_auth_token(
        expiration=3600), 'expiration': 3600})
